package com.laoxu.java.security;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.Base64;

/**
 * Base64编码测试类
 *
 * @author laoxu
 * @create 2017-12-19
 **/
public class TestBase64 {
    public static final String toEncode="Hello Base64!";

    /**
     * jdk8以前
     * @throws IOException
     */
    public static void TestBase64Old() throws IOException {
        //编码
        BASE64Encoder encoder=new BASE64Encoder();
        String encoded = encoder.encode(toEncode.getBytes());
        System.out.println("编码后："+encoded);

        //解码
        BASE64Decoder decoder=new BASE64Decoder();
        byte[] decoded = decoder.decodeBuffer(encoded);
        System.out.println("解码后："+new String(decoded));

    }

    /**
     * jdk1.8后
     */
    public static void TestBase64New(){
        //编码
        String encoded = Base64.getEncoder().encodeToString(toEncode.getBytes());
        System.out.println("编码后："+encoded);
        //解码
        byte[] decoded = Base64.getDecoder().decode(encoded);
        System.out.println("解码后："+new String(decoded));
    }


    public static void main(String[] args) throws IOException {
        System.out.println("Before JDK1.8：");
        TestBase64Old();
        System.out.println("After JDK1.8：");
        TestBase64New();
    }
}
